import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, Popconfirm } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

// 获取退款记录列表
const fetchRefunds = async (params) => {
    return request('/api/v1/payment/refund', {
        method: 'GET',
        params,
    });
};

// 获取退款详情
const fetchRefundDetail = async (id) => {
    return request(`/api/v1/payment/refund/${id}`, {
        method: 'GET',
    });
};

// 审核退款
const auditRefund = async (data) => {
    return request('/api/v1/payment/refund/audit', {
        method: 'POST',
        data,
    });
};

const RefundList = () => {
    const [refunds, setRefunds] = useState([]);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [auditForm] = Form.useForm();
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    });
    const [searchParams, setSearchParams] = useState({});
    const [detailVisible, setDetailVisible] = useState(false);
    const [auditVisible, setAuditVisible] = useState(false);
    const [currentRefund, setCurrentRefund] = useState(null);
    const [auditType, setAuditType] = useState('approve'); // approve or reject

    // 获取退款记录列表
    const fetchRefundList = async () => {
        try {
            setLoading(true);
            const res = await fetchRefunds({
                page: pagination.current,
                pageSize: pagination.pageSize,
                ...searchParams,
            });
            if (res.success) {
                setRefunds(res.data || []);
            } else {
                message.error(res.message || '获取退款记录失败');
            }
        } catch (error) {
            console.error('获取退款记录出错:', error);
            message.error('获取退款记录失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchRefundList();
    }, [pagination.current, pagination.pageSize, searchParams]);

    // 查看退款详情
    const handleViewDetail = async (record) => {
        try {
            setLoading(true);
            const res = await fetchRefundDetail(record.id);
            if (res.success) {
                setCurrentRefund(res.data);
                setDetailVisible(true);
            } else {
                message.error(res.message || '获取退款详情失败');
            }
        } catch (error) {
            console.error('获取退款详情出错:', error);
            message.error('获取退款详情失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理审核
    const handleAudit = (record, type) => {
        setCurrentRefund(record);
        setAuditType(type);
        auditForm.resetFields();
        setAuditVisible(true);
    };

    // 提交审核
    const handleAuditSubmit = async (values) => {
        try {
            setLoading(true);
            const data = {
                id: currentRefund.id,
                status: auditType === 'approve' ? 'approved' : 'rejected',
                remark: values.remark,
            };

            const res = await auditRefund(data);
            if (res.success) {
                message.success(`${auditType === 'approve' ? '审核通过' : '拒绝'}成功`);
                setAuditVisible(false);
                fetchRefundList();
            } else {
                message.error(res.message || `${auditType === 'approve' ? '审核通过' : '拒绝'}失败`);
            }
        } catch (error) {
            console.error(`${auditType === 'approve' ? '审核通过' : '拒绝'}出错:`, error);
            message.error(`${auditType === 'approve' ? '审核通过' : '拒绝'}失败`);
        } finally {
            setLoading(false);
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '退款单号',
            dataIndex: 'refundNo',
            key: 'refundNo',
            width: 180,
        },
        {
            title: '订单号',
            dataIndex: 'orderNo',
            key: 'orderNo',
            width: 180,
        },
        {
            title: '用户',
            dataIndex: 'username',
            key: 'username',
            width: 120,
        },
        {
            title: '退款金额',
            dataIndex: 'amount',
            key: 'amount',
            width: 120,
            render: (text) => `¥${text.toFixed(2)}`,
        },
        {
            title: '退款原因',
            dataIndex: 'reason',
            key: 'reason',
            width: 150,
            ellipsis: true,
        },
        {
            title: '退款状态',
            dataIndex: 'status',
            key: 'status',
            width: 120,
            render: (status) => {
                let color = '';
                let text = '';
                switch (status) {
                    case 'pending':
                        color = 'gold';
                        text = '待审核';
                        break;
                    case 'approved':
                        color = 'blue';
                        text = '已审核';
                        break;
                    case 'processing':
                        color = 'cyan';
                        text = '处理中';
                        break;
                    case 'success':
                        color = 'green';
                        text = '已完成';
                        break;
                    case 'rejected':
                        color = 'red';
                        text = '已拒绝';
                        break;
                    case 'failed':
                        color = 'red';
                        text = '退款失败';
                        break;
                    default:
                        color = 'default';
                        text = status;
                }
                return <Tag color={color}>{text}</Tag>;
            },
        },
        {
            title: '申请时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 180,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => {
                const actions = [
                    <Button
                        key="view"
                        type="link"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewDetail(record)}
                    >
                        详情
                    </Button>
                ];

                // 只有待审核状态才显示审核按钮
                if (record.status === 'pending') {
                    actions.push(
                        <Popconfirm
                            key="approve"
                            title="确定要通过此退款申请吗？"
                            onConfirm={() => handleAudit(record, 'approve')}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button
                                type="link"
                                icon={<CheckOutlined />}
                                style={{ color: '#52c41a' }}
                            >
                                通过
                            </Button>
                        </Popconfirm>,
                        <Popconfirm
                            key="reject"
                            title="确定要拒绝此退款申请吗？"
                            onConfirm={() => handleAudit(record, 'reject')}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button
                                type="link"
                                icon={<CloseOutlined />}
                                danger
                            >
                                拒绝
                            </Button>
                        </Popconfirm>
                    );
                }

                return <Space>{actions}</Space>;
            },
        },
    ];

    // 处理搜索
    const handleSearch = (values) => {
        const params = {};
        if (values.refundNo) {
            params.refundNo = values.refundNo;
        }
        if (values.orderNo) {
            params.orderNo = values.orderNo;
        }
        if (values.username) {
            params.username = values.username;
        }
        if (values.status) {
            params.status = values.status;
        }
        if (values.dateRange && values.dateRange.length === 2) {
            params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
            params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
        }

        setSearchParams(params);
        setPagination({
            ...pagination,
            current: 1, // 重置到第一页
        });
    };

    // 重置搜索
    const handleReset = () => {
        form.resetFields();
        setSearchParams({});
        setPagination({
            ...pagination,
            current: 1,
        });
    };

    // 处理表格变化
    const handleTableChange = (pagination, filters, sorter) => {
        setPagination(pagination);
    };

    return (
        <PageContainer>
            <Card>
                <Form
                    form={form}
                    layout="inline"
                    onFinish={handleSearch}
                    style={{ marginBottom: 24 }}
                >
                    <Form.Item name="refundNo" label="退款单号">
                        <Input placeholder="请输入退款单号" allowClear />
                    </Form.Item>
                    <Form.Item name="orderNo" label="订单号">
                        <Input placeholder="请输入订单号" allowClear />
                    </Form.Item>
                    <Form.Item name="username" label="用户名">
                        <Input placeholder="请输入用户名" allowClear />
                    </Form.Item>
                    <Form.Item name="status" label="退款状态">
                        <Select placeholder="请选择退款状态" style={{ width: 150 }} allowClear>
                            <Option value="pending">待审核</Option>
                            <Option value="approved">已审核</Option>
                            <Option value="processing">处理中</Option>
                            <Option value="success">已完成</Option>
                            <Option value="rejected">已拒绝</Option>
                            <Option value="failed">退款失败</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item name="dateRange" label="申请时间">
                        <RangePicker
                            showTime
                            format="YYYY-MM-DD HH:mm:ss"
                            placeholder={['开始时间', '结束时间']}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                搜索
                            </Button>
                            <Button icon={<ReloadOutlined />} onClick={handleReset}>
                                重置
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>

                <Table
                    columns={columns}
                    dataSource={refunds}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    onChange={handleTableChange}
                    scroll={{ x: 1300 }}
                />

                {/* 退款详情弹窗 */}
                <Modal
                    title="退款详情"
                    visible={detailVisible}
                    onCancel={() => setDetailVisible(false)}
                    footer={[
                        <Button key="close" onClick={() => setDetailVisible(false)}>
                            关闭
                        </Button>,
                    ]}
                    width={800}
                >
                    {currentRefund && (
                        <Descriptions bordered column={2}>
                            <Descriptions.Item label="退款单号">{currentRefund.refundNo}</Descriptions.Item>
                            <Descriptions.Item label="订单号">{currentRefund.orderNo}</Descriptions.Item>
                            <Descriptions.Item label="用户名">{currentRefund.username}</Descriptions.Item>
                            <Descriptions.Item label="退款金额">¥{currentRefund.amount.toFixed(2)}</Descriptions.Item>
                            <Descriptions.Item label="退款状态">
                                <Tag color={
                                    currentRefund.status === 'pending' ? 'gold' :
                                        currentRefund.status === 'approved' ? 'blue' :
                                            currentRefund.status === 'processing' ? 'cyan' :
                                                currentRefund.status === 'success' ? 'green' :
                                                    currentRefund.status === 'rejected' || currentRefund.status === 'failed' ? 'red' : 'default'
                                }>
                                    {{
                                        'pending': '待审核',
                                        'approved': '已审核',
                                        'processing': '处理中',
                                        'success': '已完成',
                                        'rejected': '已拒绝',
                                        'failed': '退款失败',
                                    }[currentRefund.status] || currentRefund.status}
                                </Tag>
                            </Descriptions.Item>
                            <Descriptions.Item label="申请时间">{currentRefund.createdAt}</Descriptions.Item>
                            <Descriptions.Item label="退款原因" span={2}>
                                {currentRefund.reason || '-'}
                            </Descriptions.Item>
                        </Descriptions>
                    )}
                    {currentRefund && currentRefund.status === 'processing' && (<Button type="primary" onClick={() => setAuditVisible(true)}>审核</Button>)}
                </Modal>
                {/* 审核弹窗 */}
                <Modal
                    title={`${auditType === 'approve' ? '审核通过' : '拒绝'}退款申请`}
                    visible={auditVisible}
                    onCancel={() => setAuditVisible(false)}
                    footer={[
                        <Button key="back" onClick={() => setAuditVisible(false)}>
                            返回
                        </Button>,
                        <Button key="submit" type="primary" onClick={handleAuditSubmit}>
                            提交
                        </Button>,
                    ]}
                    width={600}
                    destroyOnClose
                >
                </Modal>
            </Card>
        </PageContainer>
    );
};
export default RefundList;